package com.mark.demo.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsChecker;

/**
 * <h1>
 *
 * </h1>
 *
 * @author MarkerCCC
 * @date 2020/4/27 - 16:54
 * @since 2020/4/27 - 16:54 星期一 by MarkerCCC markerccc@163.com
 */
@Slf4j
public class MarkPreAuthenticationChecks implements UserDetailsChecker {

    /**
     * 获取访问器
     */
    private MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();

    @Override
    public void check(UserDetails userDetails) {
        if (Boolean.FALSE.equals(userDetails.isAccountNonLocked())) {
            // 如果账号为锁定 为false
            log.debug("User account is locked");

            throw new LockedException(messages.getMessage(
                    "AbstractUserDetailsAuthenticationProvider.locked",
                    "User account is locked"));
        }

        if (Boolean.FALSE.equals(userDetails.isEnabled())) {
            // 如果账号没有启用
            log.debug("User account is disabled");

            throw new DisabledException(messages.getMessage(
                    "AbstractUserDetailsAuthenticationProvider.disabled",
                    "User is disabled"));
        }

        if (Boolean.FALSE.equals(userDetails.isAccountNonExpired())) {
            // 如果账号已经过期了
            log.debug("User account is expired");

            throw new AccountExpiredException(messages.getMessage(
                    "AbstractUserDetailsAuthenticationProvider.expired",
                    "User account has expired"));
        }
    }
}
